import { defineConfig, loadEnv, UserConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import viteCompression from 'vite-plugin-compression'
import AutoImport from 'unplugin-auto-import/vite'
import { createHtmlPlugin } from 'vite-plugin-html'
import VueSetupExtend from 'vite-plugin-vue-setup-extend'
import { viteMockServe } from 'vite-plugin-mock'
import { resolve } from 'path'

// https://vitejs.dev/config/
export default ({ mode }: UserConfig) => {
  // 获取.env文件里定义的环境变量
  const env = loadEnv(mode || 'development', process.cwd())
  const isBuild = mode === 'production'

  return defineConfig({
    base: env.VITE_BASE || '/',
    plugins: [
      vue(),
      VueSetupExtend(),
      createHtmlPlugin({
        minify: isBuild,
        inject: {
          data: {
            title: env.VITE_APP_TITLE || '简易网站模版'
          }
        },
        verbose: false
      }),
      env.VITE_USE_MOCK === 'true'
        ? viteMockServe({
            logger: false,
            mockPath: './mock/',
            enable: env.VITE_USE_MOCK === 'true' ? true : false,
            watchFiles: true // 监听文件内容变更
          })
        : undefined,
      viteCompression({
        // gzip压缩
        verbose: true,
        disable: false,
        threshold: 10240,
        algorithm: 'gzip',
        ext: '.gz'
      }),
      AutoImport({
        include: [
          /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
          /\.vue$/,
          /\.vue\?vue/ // .vue
        ],
        dirs: [
          'src/components/',
          'src/layout/',
          'src/assets',
          'src/router',
          'src/service/api',
          'src/store',
          'src/utils',
          'src/views',
          'src/types',
          'src/enum'
        ],
        dts: 'src/types/auto-imports.d.ts',
        imports: ['vue', 'vue-router', 'pinia', '@vueuse/core', { 'lodash-es': [['*', 'Lodash']] }],
        eslintrc: {
          enabled: true,
          filepath: './.eslintrc-auto-import.json',
          globalsPropValue: true
        }
      })
    ],
    resolve: {
      alias: {
        '@': resolve(__dirname, 'src')
      }
    },
    server: {
      port: 3125,
      host: '0.0.0.0',
      hmr: true,
      open: false,
      proxy: {
        '/api': {
          target: 'http://api01.timedg.com',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '')
        }
      }
    },
    build: {
      // chunkSizeWarningLimit: 900,
      rollupOptions: {
        output: {
          chunkFileNames: 'js/[name]-[hash:8].js',
          entryFileNames: 'js/[name]-[hash:8].js',
          assetFileNames: '[ext]/[name]-[hash:8].[ext]',
          manualChunks(id) {
            // 静态资源分拆打包
            if (id.includes('node_modules')) {
              const chunkFileNames = id.toString().split('node_modules/')[1].split('/')[0]
              // 这里需要去掉开头的. 例如.pnpm-56sdf.css,不去掉.目录删不干净
              return chunkFileNames.startsWith('.')
                ? chunkFileNames.slice(1).toString()
                : chunkFileNames.toString()
            }
          }
        }
      }
    },
    // 预加载构建配置（首屏性能)
    optimizeDeps: {
      esbuildOptions: {
        target: 'es2020'
      },
      // 提前预加载依赖，缩短首屏访问时间
      include: ['pinia', 'vue', 'vue-router', '@vueuse/core', 'lodash-es']
    }
  })
}
